<template>
    <div class="update-photo">
        <img :src="img_src" class="img-class" ref="img">
        <div class="toolbar">
            <div class="cancel" @click="$emit('close')">取消</div>
            <div class="confirm" @click="onConfirm">完成</div>
        </div>
    </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '../../../api/user'

export default {
    name: 'UpdatePhoto',
    props: {
        img_src: {
            type: [String, Object],
            required: true
        }
    },
    data() {
        return {
            cropper: null
        }
    },
    mounted() {
        const image = this.$refs.img
        this.cropper = new Cropper(image, {
            viewMode: 1,
            dragMode: 'move',
            aspectRatio: 1,
            autoCropArea: 1,
            cropBoxMovable: false,
            cropBoxResizable: false,
            background: false,
            movable: true
        });
    },
    methods: {
        onConfirm() {
            // console.log(this.cropper.getData());
            this.$toast.loading({
                message: '加载中...',
                forbidClick: true,
                duration: 0
            })
            try {
                this.cropper.getCroppedCanvas().toBlob(async (blob) => {
                    // updateUserPhoto(blob)
                    const formData = new FormData();

                    // Pass the image file name as the third parameter if necessary.
                    formData.append('photo', blob);
                    const { data } = await updateUserPhoto(formData)
                    console.log(data);
                    this.$emit('close')
                    this.$emit('updateNewPhoto', data.data.photo)
                    this.$toast.success('更新头像成功')
                })
            } catch (err) {
                this.$toast.fail('更新头像失败')
            }
        }
    }
}
</script>

<style scoped lang="less">
.update-photo {
    height: 100%;
    background-color: #000;

    .img-class {
        max-width: 100%;
        display: block;
    }

    .toolbar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;

        .cancel,
        .confirm {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 90px;
            height: 90px;
            font-size: 30px;
            color: #fff;
        }
    }
}
</style>